<?php
/**
 *
 * User: 罗艳忠
 * Email:luozong05@126.com
 * DateTime: 2017/5/3 16:49
 */

namespace App\Http\Controllers;
use App\Models\WechatFans;
use App\Models\WechatQrcode;
use Illuminate\Http\Request;
use Validator;

class QrcodeController extends Controller
{
    public $wechatQrcodeModel;
    public $wechatFansModel;
    function __construct(Request $request, WechatQrcode $wechatQrcode, WechatFans $wechatFans){
        parent::__construct();
        $this->request = $request;
        $this->wechatQrcodeModel = $wechatQrcode;
        $this->wechatFansModel = $wechatFans;
    }

    public function index(){
        $this->data["param"] = $this->request->only("city", "name", "startDate", "endDate");
        $param = array_filter($this->data["param"]);
        $where = [];

        if(isset($param['city'])){
            $where[] = ["scene_name", "like", "%".$param["city"]."%"];
        }
        if(isset($param['name'])){
            $where[] = ["scene_name", "like", "%".$param["name"]."%"];
        }
        if(isset($param['startDate'])){
            $subwhere[] = ["subscribetime", ">", strtotime($param["startDate"])];
        }
        if(isset($param['endDate'])){
            $subwhere[] = ["subscribetime", "<", strtotime($param["endDate"])+24*60*60];
        }
        $this->data["list"]  = $this->wechatQrcodeModel->where($where)->paginate(10);
        foreach ($this->data['list'] as $qrcode) {
            $subwhere["event_key"] = $qrcode->id;
            $subwhere[] = ['subscribe_time','>',0];
            //\DB::enableQueryLog();
            $qrcode->fans_count = $this->wechatFansModel->where($subwhere)->count();
            //var_dump(\DB::getQueryLog());die;
        }
        return $this->showView("qrcode_index");
    }

    public function edit(){
        if($this->request->id){
            $wechatqrcode = $this->wechatQrcodeModel->find($this->request->id);
            $arr = explode("_", $wechatqrcode->scene_name);
            $wechatqrcode->city = $arr[0];
            $wechatqrcode->name = isset($arr[1])?$arr[1]:"";
        }else{
            $wechatqrcode = null;
        }
        $this->data["wechatQrcode"] = $wechatqrcode;
        return $this->showView("qrcode_edit");
    }

    public function save(){
        $rules = [
            "city" => "required",
            "name" => "required",
            "keyword" => "required"
        ];

        $validator = Validator::make($this->request->all(),$rules);
        if($validator->fails()){
            return back()->withErrors($validator->errors());
        }

        //$param = $this->request->only("scene_name", "keyword");
        $param['scene_name'] = $this->request->get("city")."_".$this->request->get("name");
        $param['keyword'] = $this->request->get("keyword");


        if($this->request->id){
            $wechatqrcode = $this->wechatQrcodeModel->find($this->request->id)->update($param);
        }else{
            if(!empty($this->wechatQrcodeModel->where("scene_name", $param['scene_name'])->first())){
                return back()->with("alert",["message"=>"名称已存在","style"=>"danger"]);
            }

            $param["createtime"] = time();
            $param["ticket"] = '';
            $param["expiretime"] = 0;
            $param["scan_times"] = 0;
            $param["scan_fans"] = 0;
            $qrcode = $this->wechatQrcodeModel->create($param);


            $easyQrcode = \EasyWeChat::qrcode();
            $result = $easyQrcode->forever($qrcode->id);// 或者 $qrcode->forever("foo");
            $qrcode->ticket = $result->ticket;
            $qrcode->qrcode_url = $easyQrcode->url($result->ticket);

            if($qrcode_content = file_get_contents($qrcode->qrcode_url)) { // 得到二进制图片内容
                $qrcode_url = "/qrcode/" . md5($qrcode->id) . ".jpg";
                //file_put_contents($qrcode_url, $qrcode_content);
                if (\Storage::put($qrcode_url, $qrcode_content)) {
                    $material = \EasyWeChat::material();
                    $material_result = $material->uploadImage(public_path("upload/".$qrcode_url));
                    $qrcode->qrcode_media_id = $material_result->media_id;
                }
            }
            $qrcode->update();
        }
        return redirect("qrcode")->with("alert",["message"=>"二维码添加成功","style"=>"success"]);
    }

    public function delete(){
        $this->wechatQrcodeModel->find($this->request->id)->delete();
        return redirect("qrcode")->with("alert",["message"=>"二维码删除成功","style"=>"success"]);
    }

    public function fanslist(){
        $this->data["fansList"] = $this->wechatFansModel->with("scene")->where("event_key",$this->request->scene_id)->paginate(10);
        return $this->showView("qrcode_fanslist");
    }

    public function export(){
        $param = array_filter($this->request->only("city", "name", "startDate", "endDate"));
        $where = [];
        if(isset($param['city'])){
            $where[] = ["scene_name", "like", "%".$param["city"]."%"];
        }
        if(isset($param['name'])){
            $where[] = ["scene_name", "like", "%".$param["name"]."%"];
        }
        if(isset($param['startDate'])){
            $where[] = ["createtime", ">", strtotime($param["startDate"])];
        }
        if(isset($param['endDate'])){
            $where[] = ["createtime", "<", strtotime($param["endDate"])+24*60*60];
        }

        $data = $this->wechatQrcodeModel->where($where)
            ->select(["ID","scene_name as 名称","keyword as 自动回复","scan_times as 扫描次数",
                "scan_fans as 关注人数","qrcode_url as 二维码图片路径",
            ])->get();
        if ($data) {
            \Excel::create('qrcode', function ($excel) use ($data) {
                $excel->sheet('二维码列表', function ($sheet) use ($data) {
                    $sheet->with($data);
                });
            })->download('xls');
        }
    }



}